package com.epam.utils.mail;

import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.*;

import org.apache.log4j.Logger;

import com.epam.entity.Request;

@HotMail
public class MailHotmail implements Mail {

	private static Logger logger = Logger.getLogger(MailHotmail.class);
	private Request request;
	private String message;

	public void setRequest(Request request) {
		this.request = request;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	@Override
	public void run() {

		String smtpServer = "smtp.gmail.com";
		String to = request.getClient().getEmail();
		String from = "oleg.tymchak@gmail.com";
		String subject = "Car request";
		String emailContent = "Your \n" + request.toString() + "\nwas " + message;

		Properties props = new Properties();

		props.setProperty("mail.transport.protocol", "smtps");
		props.setProperty("mail.host", smtpServer);
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "587");

		Session session = Session.getDefaultInstance(props, null);
		Message mailMessage = new MimeMessage(session);

		try {
			mailMessage.setRecipient(Message.RecipientType.TO,
					new InternetAddress(to));
			mailMessage.setFrom(new InternetAddress(from));
			mailMessage.setSubject(subject);
			mailMessage.setText(emailContent);

			Transport transport = session.getTransport("smtp");
			transport.connect(smtpServer, 587, from, "0xDEADBEAF");
			transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
			transport.close();
		} catch (MessagingException e) {
			logger.error(e.toString(), e);
		}
	}

}
